# -*- coding: utf-8 -*-
#Kontrolcu library
from os import name as platformName
from os import (sep, stat, popen)
from os import path as Path
import sys
import hashlib
import urllib

def getlibversion():
    return "2.0"

class CUnit:
    def __init__(self, path="", value=""):
        self.Address = path
        self.Name = path.split(sep)[-1]
        self.ValueReal = ""
        self.ValueReceived = value
        self.CompValue = False

    def CheckSum(self, ConType):
        ConFile = open(self.Address, "rb")
        a = ConType()

        if stat(self.Address).st_size < 50*(1024**2):  #No Progress bar
            byte = 1024*2
            while byte:
                part = ConFile.read(byte)
                a.update(part)
                byte=len(part)

        else:  #With Progress bar
            wheel = ("\\", "|", "/", "-")
            tour = 50

            byte = stat(self.Address).st_size/100
            for digit in range(101):
                part = ConFile.read(byte)
                a.update(part)
                byte=len(part)
                self.fProgressbar(wheel, tour, digit)
            print("\bDone")

        self.ValueReal = a.hexdigest()

    def Compare(self):
        Controls = { 32 : hashlib.md5,
                     40 : hashlib.sha1,
                     56 : hashlib.sha224,
                     64 : hashlib.sha256,
                     96 : hashlib.sha384,
                    128 : hashlib.sha512 }
        ConType = Controls.get(len(self.ValueReceived))
        if ConType == None:
            raise TypeError, _("Wrong control summary")
        else:
            self.CheckSum(ConType)
            if self.ValueReceived == self.ValueReal:
                self.CompValue=True

    def fFileName(self):
        rows, columns = popen("stty size", "r").read().split()
        namespace = int(columns) - 64
        if len(self.Name) > namespace:
            return self.Name[:(namespace-3)] + "..."
        else:
            return self.Name + (namespace - len(self.Name)) * " "

    def fWheel(self, wheel, digit):
        return wheel[digit%4]

    def fSpaces(self, tour, digit):
        return "[" + digit / 2 * "=" + (tour - digit / 2) * " " + "]"
 
    def fProgressbar(self, wheel, tour, digit):  #Thanks to Gökmen Görgen
        sys.stdout.write("\r%s  %s %%%s %s" % (self.fFileName(),
                                               self.fSpaces(tour, digit),
                                               digit,
                                               self.fWheel(wheel, digit)))
        sys.stdout.flush()

def FromFileCheck(File, Address=None):
    Files = FromFile(File, Address)
    Output = {}

    for i in Files.keys():
        if Files[i] == "0":
            Output[i] = "0"
        elif not len(i) in [32,40,56,64,96,128]:
            raise TypeError, _("Wrong control summary")
        else:
            Object = CUnit(path=Files[i], value=i)
            Object.Compare()

            if Object.CompValue:
                if Output.has_key(Object.Name) and Output[Object.Name] == "-":
                    pass
                else:
                    Output[Object.Name] = "+"
            else:
                Output[Object.Name] = "-"

    return Output

def FromFile(File, Address=None):
    ContFile = urllib.urlopen(File)
    ContFileRead = ContFile.read().decode("utf-8")
    ContFile.close()
    ContLines = ContFileRead.split("\n")[:-1]

    Files={}

    for i in ContLines:
        ContValue = i.split()[0]
        if not len(ContValue) in [32,40,56,64,96,128]:
            if ContValue[0] == "#":
                pass
            else:
                raise TypeError, _("Wrong control summary")
        else:
            FileName = i[len(ContValue)+2:]
            if Path.isfile(FileName):
                Files[ContValue] = FileName
            elif Path.isfile(Path.split(File)[0] + sep + FileName):
                Files[ContValue] = Path.split(File)[0] + sep + FileName
            elif Address and Path.isfile(Address + sep + FileName):
                Files[ContValue] = Address + sep + FileName
            else:
                Files[FileName] = "0"
                pass

    return Files

    

# Making Colorful Debugging Texts
class bcolors:
    HEADER = '\033[95m' # Pink
    OKBLUE = '\033[94m' # Blue
    OKGREEN = '\033[92m' # Green
    WARNING = '\033[93m' # Yellow
    FAIL = '\033[91m' # Red
    ENDC = '\033[0m' # Finish

def makeBlue(text=""):
    if platformName == "posix":
       return bcolors.OKBLUE + text + bcolors.ENDC
    else: # If nt return no color because nt has no soul :)
       return text
def makeRed(text=""):
    if platformName == "posix":
       return bcolors.FAIL + text +bcolors.ENDC
    else:
       return text
def makeGreen(text=""):
    if platformName == "posix":
       return bcolors.OKGREEN + text + bcolors.ENDC
    else:
       return text
def makePink(text=""):
    if platformName == "posix":
       return bcolors.HEADER + text + bcolors.ENDC
    else:
       return text
def makeYellow(text=""):
    if platformName == "posix":
       return bcolors.WARNING + text + bcolors.ENDC
    else:
       return text

def testColors():
    print makeBlue("+"*20)
    print makeRed("+"*20)
    print makeGreen("+"*20)
    print makePink("+"*20)
    print makeYellow("+"*20)
